package com.aji.alluser.controller;


import com.aji.allcommon.result.Result;
import com.aji.allcommon.utills.JwtUtil;
import com.aji.alluser.constant.JwtClaimsConstant;
import com.aji.alluser.domain.LoginUser;
import com.aji.alluser.domain.RoleUser;
import com.aji.alluser.domain.User;
import com.aji.alluser.domain.dto.LoginDto;
import com.aji.alluser.domain.dto.RegisterDto;
import com.aji.alluser.domain.vo.LoginVo;
import com.aji.alluser.domain.vo.UserInfo;
import com.aji.alluser.properties.JwtProperties;
import com.aji.alluser.service.LoginService;
import com.aji.alluser.service.RoleUserService;
import com.aji.alluser.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/login")
@Slf4j
@Api(tags = "登录相关接口")
//预留用来管理多个用户，暂时只用一个
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleUserService roleUserService;
    /**
     * 登录
     *
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    @Transactional
    public Result<LoginVo>login(@RequestBody LoginDto loginDto){
        log.info("用户登录：{}",loginDto);
        User user = loginService.login(loginDto);
        //登录成功后，生成jwt令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        List<String> stringList = loginService.selectPermsByUserId(user.getId());
        claims.put("menus",stringList);
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        List<Integer> roleList = roleUserService.getRoleById(user.getId());
        System.out.println("roleList:"+roleList);

        LoginVo loginVo = LoginVo.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .roleUserList(roleList)
                .build();
        return Result.success(loginVo);
    }

    @ApiOperation("获取 用户权限信息")// todo 添加头像信息 先改数据库
    @GetMapping("/userInfo")
    public Result userInfo(String token){
        UserInfo userInfo = loginService.userInfo(token);
        return Result.success(userInfo);
    }
    @ApiOperation(value = "用户登出")
    @PostMapping("/logout")
    public  Result logout(){
        return Result.success();
    }
    @ApiOperation("注册 需要忽略id")
    @PostMapping("/register")
    public Result register(@RequestBody RegisterDto registerDto){ // todo 添加头像信息
        User entity = User.builder()
                .createTime(LocalDateTime.now())
                .name(registerDto.getName())
                .username(registerDto.getUsername())
                .phone(registerDto.getPhone())
                .school(registerDto.getSchool())
                .status(0)//禁用
                .build();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode(registerDto.getPassword());
        entity.setPassword(password);
        userService.save(entity);
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .select().eq(User::getUsername,entity.getUsername());
        RoleUser roleUser = RoleUser.builder()
                .roleId(2)//设置为普通权限
                .userId(userService.getOne(userLambdaQueryWrapper).getId())
                .build();
        roleUserService.save(roleUser);
        return Result.success();
    }
}
